package com.huizhonglm.diap.ui.app;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.model.user.MyWalletResponse;
import com.huizhonglm.diap.api.model.user.OrderInfo;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.presenters.user.OrderListPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.LoginActivity;
import com.huizhonglm.diap.ui.user.iView.OrderListIView;
import com.huizhonglm.diap.ui.wallet.PaymentActivity;
import com.huizhonglm.diap.widget.LoadView;

import java.util.List;

/**
 * 浏览器
 */
public class BrowserActivity extends BaseActivity implements OrderListIView {

    private TextView titleTxt;
    private WebView mWebView;
    private LoadView mLoadView;

    private boolean hasTitle = false;
    private OrderListPresenter mPresenter;
    private MyWalletResponse mMyWallet;
    private String mWebAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        setBackEvent(this, null);
        assignViews();
        mPresenter = new OrderListPresenter(this);
        mPresenter.loadMyWallet();
        Intent intent = getIntent();
        String title = intent.getStringExtra("webTitle");
        mWebAddress = intent.getStringExtra("webAddress");
        loadWebPage(title, mWebAddress);
    }

    @Override
    protected void assignViews() {
        titleTxt = (TextView) findViewById(R.id.page_title_txt);
        mLoadView = (LoadView) findViewById(R.id.load_view);
        initWebView();
//		mWebView.setBackgroundColor(0);
//		Drawable bg = mWebView.getBackground();
//		if (bg != null) {
//			bg.setAlpha(0);
//		}
        mLoadView.setDataView(mWebView, new LoadView.OnLoadAgainListener() {
            @Override
            public void onLoadAgain() {

            }
        });
    }

    private void loadWebPage(String title, String url) {
        if (!EmptyUtil.isEmpty(title)) {
            hasTitle = true;
            titleTxt.setText(title);
        } else {
            hasTitle = false;
            titleTxt.setText("");
        }
        if (!EmptyUtil.isEmpty(url)) {
            mLoadView.showProgress();
            mWebView.setVisibility(View.VISIBLE);
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.clearFormData();
            mWebView.loadUrl(url);
        } else {
            mLoadView.showEmptyView("页面地址异常");
        }
    }

    public final WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress >= 100) {
                mLoadView.showDataView();
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (!hasTitle && titleTxt != null) {
                titleTxt.setText(title);
            }
        }
    };

    private void initWebView() {
        mWebView = (WebView) findViewById(R.id.browser_web);
        WebSettings ws = mWebView.getSettings();
        // 适应手机屏幕：
        ws.setUseWideViewPort(true);
        ws.setLoadWithOverviewMode(true);
        // 放大设置：
        ws.setDisplayZoomControls(false);
        // 无限放大：
        ws.setSupportZoom(false);
        // 缩放至屏幕的大小
        ws.setLoadWithOverviewMode(true);
        // 支持自动加载图片
        ws.setLoadsImagesAutomatically(true);
        // 实际应用中，一般配置即可满足基本需求
        ws.setJavaScriptEnabled(true);
        ws.setDefaultTextEncodingName("utf-8");
        // 设置 缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        ws.setDomStorageEnabled(true);
        /**
         * Webview在安卓5.0之前默认允许其加载混合网络协议内容
         * 在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // 设置初始缩放大小

        mWebView.setWebChromeClient(mWebChromeClient);
        //覆盖系统浏览器打开，使目标在webview中打开
        mWebView.setWebViewClient(new MyWebViewClient());
    }

    /**
     * WebView 页面跳转，错误处理重写
     * <p/>
     * 创建时间: 2014年12月30日 下午6:21:31 <br/>
     *
     * @author xnjiang
     * @version WebViewActivity
     * @since v0.0.10
     */
    public class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (!UserUtil.isLogin() && url.contains("http://www.huizhonglm.com/index/contact.html")) {
                finish();
                startActivity(new Intent(BrowserActivity.this, LoginActivity.class));
            } else {
                if (url.contains("http://www.huizhonglm.com/mobile/index/active/paied")) {
                    openPaymentPage(url);
                } else {
                    view.loadUrl(url);
                }
            }
            return true;//ture为在webview中打开
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // 屏蔽掉错误信息.
            // handleLoadError(view);
        }

        /**
         * 核心解决加载https页面的时候空白页面的问题
         */
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //handler.cancel(); // Android默认的处理方式，WebView变成空白页
            handler.proceed(); // 接受所有网站的证书，系统就会忽略证书的错误继续Load页面内容，不会显示空白页面
            // handleMessage(Message msg); // 进行其他处理
        }
    }

    @Override
    public void onLoadDataSuccess(String pullFlag, List<OrderInfo> data) {

    }

    @Override
    public void onLoadDataFailure(String pullFlag) {

    }

    @Override
    public void onLoadDataEmpty(String pullFlag) {

    }

    @Override
    public void onLoadMyWalletSuccess(MyWalletResponse resp) {
        mMyWallet = resp;
    }

    @Override
    public void onLoadMyWalletFailure() {

    }

    /**
     * 跳转支付页面
     *
     * @param url
     */
    private void openPaymentPage(String url) {

//		String path = "http://www.test.com/payment_m.aspx?action=confirm&order_no=on123456&order_money=99.99&return_url=test/return_url.aspx";
//		Uri uri = Uri.parse(path);
//		String action = uri.getQueryParameter("action"); //解析参数
//		String order_no = uri.getQueryParameter("order_no");//解析参数
//		String order_money = uri.getQueryParameter("order_money");//解析参数
//		String return_url = uri.getQueryParameter("return_url");//解析参数
//		String pa = uri.getLastPathSegment();//解析最后一个地址段，即payment_m.aspx
//		System.out.println(
//				"parse_uri==>"+action+"\n"
//						+order_no+"\n"
//						+order_money+"\n"
//						+return_url+"\n"
//						+pa);
        OrderInfo order = new OrderInfo();
        Uri uri = Uri.parse(url);
        String orderId = uri.getQueryParameter("orderId"); //解析参数
        String totalPrice = uri.getQueryParameter("totalPrice");//解析参数

        order.setShopId("8aae324f5a5911c9015ac62334350020");
        order.setOrderId(orderId);
        order.setTotalPrice(Double.parseDouble(totalPrice));
        if (mMyWallet != null) {
            Intent payPage = new Intent(this, PaymentActivity.class);
            payPage.putExtra("wallet", mMyWallet);
            payPage.putExtra("order", order);
            startActivity(payPage);
        } else {
            ToastUtil.makeTextShort("初始化付款失败，请稍后重试");
        }
    }
}
